package com.franklin.ideaplugin.api.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则表达式工具类
 *
 * @author Ye Junhui
 * @since 2023/2/1 0001
 */
public class PatternUtil {

    /**
     * 正则填值
     * @param keyValueMap
     * @param target
     * @return
     */
    public static String fillValues(Map<String,? extends Object> keyValueMap, String target, Pattern pattern){
        if (CollectionUtil.isEmpty(keyValueMap)){
            return target;
        }
        Matcher matcher = pattern.matcher(target);
        String result = target;
        while (matcher.find()){
            String key = matcher.group(1);
            Object value = keyValueMap.get(key);
            String valueStr = Objects.isNull(value) ? "" : value.toString();
            result = matcher.replaceFirst(valueStr);
            matcher = pattern.matcher(result);
        }
        return result;
    }

    /**
     * 查找参数key
     * @param target
     * @param pattern
     * @return
     */
    public static List<String> findKeys(String target, Pattern pattern){
        Matcher matcher = pattern.matcher(target);
        String result = target;
        Set<String> set = Sets.newLinkedHashSet();
        while (matcher.find()){
            String key = matcher.group(1);
            result = matcher.replaceFirst("");
            matcher = pattern.matcher(result);
            set.add(key);
        }
        return Lists.newArrayList(set);
    }
}
